﻿using System;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using OpenLS.Spreadsheet.Expressions;

namespace OpenLS.Spreadsheet
{
    abstract class  ExpressionFormula: CellFormulaBase
    {
        protected abstract Worksheet Worksheet { get; }
        private readonly Expression _expression;

        public ExpressionFormula(Expression expression)
        {
            Contract.Requires(expression != null);
            _expression = expression;
        }

        public override string Text
        {
            get
            {
                Contract.Ensures(CellFormulaBase.Parse(Contract.Result<string>(), this.Worksheet) is ExpressionFormula);
                Debug.WriteLine(this.Expression);
                return "=" + Expression.GetText(new TextContext(new WorksheetEvaluationContext(Worksheet)));
            }
        }
        public override string TextWithoutEqual
        {
            get
            {
                Contract.Ensures(CellFormulaBase.Parse("="+Contract.Result<string>(), this.Worksheet) is ExpressionFormula);
                Debug.WriteLine(Expression);
                var result =  Expression.GetText(new TextContext(new WorksheetEvaluationContext(Worksheet)));
#if DEBUG
                var t = CellFormulaBase.Parse("=" + result, this.Worksheet);
                Contract.Assert(t is ExpressionFormula);
#endif
                return result;
            }
        }

        public Expression Expression
        {
            get { return _expression; }
        }


    }
}